package org.xiaojinlong.exam;

public class Box {
    private int index = 0;
    Apple[] arrApple = new Apple[5];

    // 放苹果
    public synchronized void push(Apple app){
        while (index == arrApple.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        arrApple[index]=app;
        index++;
    }

    // 拿苹果
    public synchronized  Apple pop(){
        while(index == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        index--;
        return arrApple[index];
    }
}

class Apple {
    private static int count = 0;
    int id;
    Apple() {
        this.id = count;
        count++;
    }
    public String toString() {
        return "Apple[" + id + "]";
    }
}

class PClient implements Runnable {
    private Box box =null;
    public PClient(Box box){
        this.box = box;
    }

    @Override
    public void run() {
        while (true) {
            Apple mt= new Apple();
            box.push(mt);
            System.out.println("放苹果："+mt);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

class VClient implements Runnable {
    private Box box = null;
    public VClient(Box box){
        this.box = box;
    }
    @Override
    public void run() {
        while (true) {
            Apple mt = box.pop();
            System.out.println("拿苹果: " + mt);
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class PVClient {
    public static void main(String[] args) {
        Box box = new Box();
        PClient p = new PClient(box);
        VClient v= new VClient(box);

        new Thread(p).start();
        new Thread(v).start();
    }

}


